package com.etoak.common.web.handler;


import com.etoak.common.core.exception.CustomException;
import com.etoak.common.core.vo.ResultVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.stream.Collectors;

@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler {

    @ExceptionHandler
    public ResultVO<String> exceptionHandler(MethodArgumentNotValidException ex) {
        log.error(ex.getMessage(), ex);

        // ex主要涵盖的是 没有通过的javabean上的注解
        // ex 里面含有每一个注解上的信息
        String msg = ex.getAllErrors()
                .stream()
                .map(ObjectError::getDefaultMessage)
                .collect(Collectors.joining(";"));

        return ResultVO.failed(msg);
    }

    @ExceptionHandler
    public ResultVO<String> exceptionHandler(CustomException ex) {
        log.error(ex.getMessage(), ex);
        return ResultVO.failed(ex.getMessage());
    }

    @ExceptionHandler
    public ResultVO<String> exceptionHandler(Exception ex) {
        log.error(ex.getMessage(), ex);
        return ResultVO.failed(ex.getMessage());
    }
}